package com.example.yin.controller;

import com.example.yin.common.R;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.Gson;
import org.springframework.http.*;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.Map;
//import java.nio.file.Files;
//import java.nio.file.Path;
//import java.nio.file.Paths;
//import java.nio.file.StandardCopyOption;

import static com.example.yin.constant.Constants.*;

/**
 * @author 北煜
 */
@RestController
@RequestMapping("/voice")
public class VoiceController {

    @PostMapping("/UseVoice")
    public R useVoice(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return R.error("未选择文件");
        }
        String fileName = file.getOriginalFilename();
//            Path filePath = Paths.get(UPLOAD_DIRECTORY, fileName);
//            Files.copy(file.getInputStream(), filePath, StandardCopyOption.REPLACE_EXISTING);
        // 构造一个带指定Region对象的配置类
        Configuration cfg = new Configuration(Region.region2());
        cfg.resumableUploadAPIVersion = Configuration.ResumableUploadAPIVersion.V2;
        UploadManager uploadManager = new UploadManager(cfg);
        Auth auth = Auth.create(ACCESS_KEY_QINIU, SECRET_KEY_QINIU);
        String bucketName = BUCKET_NAME_QINIU;
        String key = "flh" + "/" + fileName;
        String baseUrl = "http://qiniuyun.linter.top";
        String url = baseUrl + "/" + key;
        byte[] fileContent = new byte[0];
        try {
            fileContent = file.getBytes();
            try (ByteArrayInputStream inputStream = new ByteArrayInputStream(fileContent)) {
                String upToken = auth.uploadToken(bucketName, key);
                Response response = uploadManager.put(inputStream, key, upToken, null, null);
                DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
                // 上传结果处理
                if (response.statusCode == 200) {
                    RestTemplate restTemplate = new RestTemplate();
                    // 构造请求参数
                    MultiValueMap<String, Object> params = new LinkedMultiValueMap<>();
                    params.add("url", url);
                    HttpHeaders headers = new HttpHeaders();
                    // 设置Content-Type为表单类型
                    headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
                    HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(params, headers);
                    ResponseEntity<String> res = restTemplate.postForEntity("http://127.0.0.1:5000/Voice",
                            requestEntity, String.class);
                    // 处理响应结果
                    if (res.getStatusCode().is2xxSuccessful()){
                        System.out.println(res.getBody());
                        String responseBody = res.getBody();
                        ObjectMapper objectMapper = new ObjectMapper();
                        Map<String, String> resultMap = objectMapper.readValue(responseBody, new TypeReference<Map<String, String>>(){});
                        // 获取extracted_text的值
                        String extractedText = resultMap.get("extracted_text");
                        System.out.println(extractedText);
                        return R.success(extractedText);
                    }
                    return R.error(putRet.hash + ": " + "上传成功！");
                } else {
                    throw new RuntimeException("上传失败" + ": " + response.bodyString());
                }
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
